//
//  AddInvoiceViewController.m
//  云律司
//
//  Created by 韦淋 on 2017/8/4.
//  Copyright © 2017年 test. All rights reserved.
//

#import "AddInvoiceViewController.h"

@interface AddInvoiceViewController ()<JHPickerDelegate,UITextFieldDelegate,UITextViewDelegate>

{
    NSMutableArray *caseNum;
    BOOL isHaveDian;
    NSString *caseId;
}

@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *placeHolderArray;
@property (nonatomic, strong) NSArray *starArray;
@property (nonatomic, strong) NSArray *kpxm_Type;
@property (nonatomic, strong) NSArray *kplx_Type;
@property (nonatomic, strong) NSArray *fplx_Type;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSString *selectStr;
@property (nonatomic, assign) NSInteger seletTag;
@end

@implementation AddInvoiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = false;
    self.dataSource = [NSMutableArray array];
    caseNum = [NSMutableArray array];
    for (NSDictionary *dic in self.caseNumArray) {
        [caseNum addObject:dic[@"ah_number"]];
        NSLog(@"dic:%@",dic);
    }
    NSLog(@"caseNum:%@",caseNum);
    self.view.backgroundColor = [UIColor whiteColor];
    [self initUI];
}
#pragma mark - Private Method
- (void)initUI{
//    [self.view addSubview:self.scrollView];
    
        self.barTitleLable.text = @"发票详情";
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
        scrollView.contentSize = CGSizeMake(0, SCREEN_HEIGHT *2 + 150);
    
    scrollView.delegate = self;
    [self.view insertSubview:scrollView atIndex:0];
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 2 + 150)];
    backView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:backView];
    
    for (int i = 0; i < self.titleArray.count; i ++) {
        
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(10, 80 + i * 50, self.view.bounds.size.width - 20, 40)];
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.layer.borderWidth = 1.0f;
        bgView.layer.borderColor = [[UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f] CGColor];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, 40, 40)];
        view.backgroundColor = [UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f];
        
        UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 120, 40)];
        titleLable.textColor = [UIColor blackColor];
        titleLable.backgroundColor = [UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f];
        titleLable.font = [UIFont systemFontOfSize:13];
        titleLable.text = self.titleArray[i];
        
        UILabel *redStar = [[UILabel alloc] initWithFrame:CGRectMake(130, 0, 10, 40)];
        redStar.textColor = [UIColor redColor];
        redStar.backgroundColor = [UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f];
        redStar.font = [UIFont systemFontOfSize:12];
        redStar.text = self.starArray[i];
        
        [backView addSubview:bgView];
        
        [bgView addSubview:titleLable];
        [bgView addSubview:redStar];
        
        UITextField *inputInfo = [[UITextField alloc] initWithFrame:CGRectMake(160, 80 + i * 50, 200, 40)];
        inputInfo.clearButtonMode = UITextFieldViewModeWhileEditing;
        inputInfo.textAlignment = NSTextAlignmentLeft;
        inputInfo.font = [UIFont systemFontOfSize:12];
        inputInfo.placeholder = self.placeHolderArray[i];
        inputInfo.delegate = self;
        
        UIButton *button_textFiled = [[UIButton alloc] initWithFrame:CGRectMake(160, 80 + i * 50, 200, 40)];
        [button_textFiled addTarget:self action:@selector(textFieldsDidClick:) forControlEvents:(UIControlEventTouchUpInside)];
        inputInfo.tag = i + 100;
        button_textFiled.tag = i + 100;
        
        
        if (i == 2) {
            inputInfo.userInteractionEnabled = NO;
        }
        if (i == 3) {
            inputInfo.userInteractionEnabled = NO;
        }
        if (i == 4) {
            inputInfo.userInteractionEnabled = NO;
        }
        if (i == 6) {
            inputInfo.userInteractionEnabled = NO;
        }
        if (i == 7) {
            inputInfo.userInteractionEnabled = NO;
        }
        if (i == 0 || i == 8 || i == 9 || i == 10 || i == 22) {
            inputInfo.text = self.selectStr;
            button_textFiled.hidden = NO;
        }
        
        else{
            if (i == 11) {
                inputInfo.keyboardType = UIKeyboardTypeDecimalPad;
                
            }
            if (i == 16 || i == 19) {
                inputInfo.keyboardType = UIKeyboardTypePhonePad;
            }
            button_textFiled.hidden = YES;
        }
        
        UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        grayView.backgroundColor = [UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f];
        
        if (i == self.titleArray.count - 1) {
            bgView.frame = CGRectMake(10, 80 + i * 50, 130, 40);
            inputInfo.hidden = YES;
            
            UITextView *input = [[UITextView alloc] initWithFrame:CGRectMake(10, 80 + (i + 1) * 50, self.view.bounds.size.width - 20, 120)];
            input.layer.borderWidth = 1.0f;
            input.layer.borderColor = [[UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f] CGColor];
            input.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            input.text = @"请填写备注";
            input.tag = 1000;
            input.textColor = [UIColor lightGrayColor];
            input.delegate = self;
            [backView addSubview:input];
            
            
            UIButton *putInButton = [UIButton buttonWithType:UIButtonTypeCustom];
            putInButton.frame = CGRectMake(20, 80 + (i + 1) * 50 + 130, self.view.bounds.size.width - 40, 40);
            [putInButton setTitle:@"发起申请" forState:UIControlStateNormal];
            putInButton.titleLabel.textColor = [UIColor whiteColor];
            putInButton.layer.cornerRadius = 5;
            putInButton.layer.masksToBounds = YES;
            putInButton.backgroundColor = [UIColor colorWithRed:33.0f/255.0f green:180.0f/255.0f blue:237.0f/255.0f alpha:1.0f];
            [putInButton addTarget:self action:@selector(action_Submit) forControlEvents:UIControlEventTouchUpInside];
            [backView addSubview:putInButton];
        }
        [bgView addSubview:grayView];
        [backView addSubview:inputInfo];
        [backView addSubview:button_textFiled];
//        [bgView insertSubview:view belowSubview:grayView];
        

            
        }
    
        
}
#pragma mark - Button Target
- (void)action_Submit{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *nowtimeStr = [formatter stringFromDate:datenow];
    NSLog(@"nowtimeStr =  %@",nowtimeStr);
    

    UITextField *textField = [self.view viewWithTag:100];
    UITextField *textField1 = [self.view viewWithTag:101];
//    UITextField *textField2 = [self.view viewWithTag:102];
//    UITextField *textField3 = [self.view viewWithTag:103];
//    UITextField *textField4 = [self.view viewWithTag:104];
    UITextField *textField2 = [self.view viewWithTag:105];
//    UITextField *textField6 = [self.view viewWithTag:106];
//    UITextField *textField7 = [self.view viewWithTag:107];
    UITextField *textField3 = [self.view viewWithTag:108];
    UITextField *textField4 = [self.view viewWithTag:109];
    UITextField *textField5 = [self.view viewWithTag:110];
    UITextField *textField6 = [self.view viewWithTag:111];
    UITextField *textField7 = [self.view viewWithTag:112];
    UITextField *textField8 = [self.view viewWithTag:113];
    UITextField *textField9 = [self.view viewWithTag:114];
    UITextField *textField10 = [self.view viewWithTag:115];
    UITextField *textField11 = [self.view viewWithTag:116];
    UITextField *textField12 = [self.view viewWithTag:117];
    UITextField *textField13 = [self.view viewWithTag:118];
    UITextField *textField14 = [self.view viewWithTag:119];
    UITextField *textField15 = [self.view viewWithTag:120];
    UITextField *textField16 = [self.view viewWithTag:121];
    UITextField *textField17 = [self.view viewWithTag:122];
    if (textField.text.length == 0) {
        NSLog(@"案号不为空 ");
        [MBProgressHUD showError:@"请选择案号"];
        return;
    }
        
    if (textField1.text.length == 0){
        NSLog(@"申请人不为空");
        [MBProgressHUD showError:@"请填写申请人"];
        return;
    }
    if (textField2.text.length == 0){
        NSLog(@"发票抬头不为空");
        [MBProgressHUD showError:@"请填写发票抬头"];
        return;
    }
    if (textField3.text.length == 0) {
        NSLog(@"开票项目不为空");
        [MBProgressHUD showError:@"请选择开票项目"];
        return;
    }
    if (textField4.text.length == 0) {
        NSLog(@"开票类型不为空");
        [MBProgressHUD showError:@"请选择开票类型"];
        return;
    }
    if (textField5.text.length == 0) {
        NSLog(@"发票类型不为空");
        [MBProgressHUD showError:@"请选择发票类型"];
        return;
    }
    if (textField6.text.length == 0) {
        NSLog(@"开票金额不为空");
        [MBProgressHUD showError:@"请填写发票金额"];
        return;
    }
    if (textField11.text.length > 0 && ![PhoneNumberFormat validateCellPhoneNumber:textField11.text]){
        NSLog(@"请检查电话号码格式");
        [MBProgressHUD showError:@"请检查注册固定电话号码格式"];
        return;
    }if (textField14.text.length > 0 && ![PhoneNumberFormat validateCellPhoneNumber:textField14.text]){
        NSLog(@"请检查电话号码格式");
        [MBProgressHUD showError:@"请检查联系电话号码格式"];
        return;
    }
    if (textField16.text.length == 0) {
        NSLog(@"发票号不为空");
        [MBProgressHUD showError:@"请填写发票号"];
        return;
    }
    
    if (textField17.text.length == 0) {
        NSLog(@"开票日期不为空");
        [MBProgressHUD showError:@"请选择开票日期"];
        return;
    }
    
    
    NSLog(@"发起申请");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSLog(@"cid = %@",[InfoSingleTon personInfoSingleTon].infoDic[@"cid"]);
    NSDictionary *dic = @{
                            @"ah_id":caseId,
                            
                            @"sqr":textField1.text,
                            
                            @"fptt":textField2.text,
                            
                            @"kpxm":[NSString stringWithFormat:@"%zd",[self.kpxm_Type indexOfObject:textField3.text] + 1],
                            
                            @"kjlx":[NSString stringWithFormat:@"%zd",[self.kplx_Type indexOfObject:textField4.text] + 1],
                            
                            @"fplx":[NSString stringWithFormat:@"%zd",[self.fplx_Type indexOfObject:textField5.text] + 1],
                            
                            @"kpje":textField6.text,
                            
                            @"nsrsbh":textField7.text,
                            
                            @"jbhkhyh":textField8.text,
                            
                            @"jbhkhzh":textField9.text,
                            
                            @"zccsdz":textField10.text,
                            
                            @"zcgddh":textField11.text,
                            
                            @"sjr":textField12.text,
                            
                            @"sjdz":textField13.text,
                            
                            @"lxdh":textField14.text,
                            
                            @"sqbz":textField15.text,
                            
                            @"fph":textField16.text,
                            
                            @"kprq":textField17.text,
                            
                            @"kpbz":@"iOS测试",
                            
                            @"zt":@"1",
                            
                            @"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],
                            
                            @"create_name":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"name"],
                            
                            @"create_time":nowtimeStr,
                            
                            @"ah_num":textField.text,
                            };
    NSLog(@"dic = %@",dic);
    [NetworkingManager postUrl:ADDINVOICE_URL dic:dic Succeed:^(id responseData) {
        
        NSLog(@"addJobLog :%@",responseData);
        NSLog(@"%@",responseData);
        [MBProgressHUD showError:@"上传成功"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [MBProgressHUD showError:@"上传失败"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    
}


//- (void)action_ClickButton:(UIButton *)sender{
//
//    NSLog(@"tag = %ld",sender.tag);
//}
- (void)textFieldsDidClick:(UIButton *)sender{
    //    if (self.flag == 0) {
    NSLog(@"tag = %ld",sender.tag);
    if (sender.tag == 100) {
        self.seletTag = 100;
        JHPickView *picker = [[JHPickView alloc]initWithFrame:self.view.bounds];
        picker.delegate = self ;
        picker.customArr = caseNum;
        [self.view addSubview:picker];
    }
    if (sender.tag == 108) {
        self.seletTag = 108;
        JHPickView *picker = [[JHPickView alloc]initWithFrame:self.view.bounds];
        picker.delegate = self ;
        picker.selectLb.text = @"请选择";
        picker.customArr = self.kpxm_Type;
        [self.view addSubview:picker];
    }
    if (sender.tag == 109) {
        self.seletTag = 109;
        JHPickView *picker = [[JHPickView alloc] initWithFrame:self.view.bounds];
        picker.delegate = self ;
        picker.selectLb.text = @"请选择";
        picker.customArr = self.kplx_Type;
        [self.view addSubview:picker];
    }
    
    if (sender.tag == 110) {
        self.seletTag = 110;
        JHPickView *picker = [[JHPickView alloc]initWithFrame:self.view.bounds];
        picker.delegate = self ;
        picker.selectLb.text = @"请选择";
        picker.customArr = self.fplx_Type;
        [self.view addSubview:picker];
    }
    if (sender.tag == 122) {
        self.seletTag = 122;
        JHPickView *picker = [[JHPickView alloc]initWithFrame:self.view.bounds];
        picker.delegate = self ;
        picker.arrayType = DeteArray;
        [self.view addSubview:picker];
    }
    
}

#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"请填写备注";
        textView.textColor = [UIColor lightGrayColor];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请填写备注"]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}
#pragma mark - UITextFiledDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if (textField.tag == 100 || textField.tag == 108 || textField.tag == 109 || textField.tag == 110 || textField.tag == 122) {
        return NO;
    }
    else{
        return YES;
    }
    
}
#pragma mark - UITextFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    /*
     *  判断输入是否为小数
     */
    //     判断是否有小数点
    NSLog(@"tex = %@  ns = %@  让 = %ld",textField.text,string,range.location);
    if ([textField.text containsString:@"."])
    {
        isHaveDian = YES;
    }else{
        isHaveDian = NO;
        
    } if (string.length > 0) {
        //当前输入的字符
        unichar single = [string characterAtIndex:0];
        NSLog(@"single = %c",single);
        
        // 不能输入.0-9以外的字符
//        if (!((single >= '0' && single <= '9') || single == '.')) {
//            [self showMyMessage:@"您的输入格式不正确" ];
//            return NO;
//        }
        
        // 只能有一个小数点
        if (isHaveDian && single == '.') {
            [self showMyMessage:@"最多只能输入一个小数点" ];
            return NO;
        }
        // 如果第一位是.则前面加上0.
        if ((textField.text.length == 0) && (single == '.')) {
            
            textField.text = @"0";
        }
        
        // 如果第一位是0则后面必须输入点，否则不能输入。
        if ([textField.text hasPrefix:@"0"]) {
            
            NSLog(@"tex = %@  ns = %@",textField.text,string);
            //            textField.text = @".";
            if (textField.text.length > 1) {
                NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                if (![secondStr isEqualToString:@"."]) {
                    [self showMyMessage:@"第二个字符需要是小数点" ];
                    return NO;
                }
            }else{
                if (![string isEqualToString:@"."]) {
                    [self showMyMessage:@"第二个字符需要是小数点" ];
                    return NO;
                }
            }
        }
        // 小数点后最多能输入两位
        if (isHaveDian) {
            NSRange ran = [textField.text rangeOfString:@"."];
            // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
            if (range.location > ran.location) {
                if ([textField.text pathExtension].length > 1) {
                    [self showMyMessage:@"小数点后最多有两位小数" ];
                    return NO;
                }
            }
        }
    }
    
    return YES;
    
}

-(void)showMyMessage:(NSString*)aInfo {
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:aInfo delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [alertView show];
    
}
#pragma mark - JHPickerViewDelegate
-(void)PickerSelectorIndixString:(NSString *)str
{
    self.selectStr = str ;
    NSLog(@"str = %@",self.selectStr);
    UITextField *textfield = [self.view viewWithTag:self.seletTag];
    if (self.seletTag == 100) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        textfield.text = str;
        NSInteger index = 0;
        if ([caseNum containsObject:str]) {
            
            index = [caseNum indexOfObject:str];
            NSLog(@"-1---%ld---",index);
        }
        NSMutableArray *caseIdArr = [NSMutableArray array];
        for (NSDictionary *dic in self.caseNumArray) {
            [caseIdArr addObject:dic[@"id"]];
        }
        NSLog(@"id = %@",caseIdArr[index]);
        caseId = caseIdArr[index];
        [NetworkingManager postUrl:[NSString stringWithFormat:@"%@create_id=%@&id=%@",CASENUMINVOICE_URL,[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],caseId] dic:nil Succeed:^(id responseData) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"success:%@",responseData);
            UITextField *textField = [self.view viewWithTag:102];
            UITextField *textField1 = [self.view viewWithTag:103];
            UITextField *textField2 = [self.view viewWithTag:104];
            UITextField *textField3 = [self.view viewWithTag:106];
            textField.text = responseData[@"result"][0][@"wtr"];
            textField1.text = responseData[@"result"][0][@"ay"];
            textField2.text = responseData[@"result"][0][@"dlf"];
            
            if ([responseData[@"result"][0][@"sfje"] isEqual:[NSNull null]]) {
                textField3.text = @"0.00";
            }
            else{
                textField3.text = responseData[@"result"][0][@"sfje"];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"error:%@",error);
            [MBProgressHUD showError:@"网络错误"];
        }];
    }else{
        
        textfield.text = str;
    }
}
#pragma mark - Getter
- (NSArray *)kpxm_Type{
    if (!_kpxm_Type) {
        _kpxm_Type = [NSArray arrayWithObjects:@"律师代理费",@"法律顾问费",@"咨询费",@"法务托管费",@"非诉",@"其他（备注中填写）",@"支付宝",@"微信",@"新增", nil];
    }
    return _kpxm_Type;
}
- (NSArray *)kplx_Type{
    if (!_kplx_Type) {
        _kplx_Type = [NSArray arrayWithObjects:@"企业",@"个人", nil];
    }
    return _kplx_Type;
}
- (NSArray *)fplx_Type{
    if (!_fplx_Type) {
        _fplx_Type = [NSArray arrayWithObjects:@"增值税专用发票",@"增值税普通发票",@"普通机打发票", nil];
    }
    return _fplx_Type;
}
- (NSArray *)titleArray{
    if (!_titleArray) {
        
        _titleArray = [NSArray arrayWithObjects:@"案号：",@"申请人：",@"委托人：",@"案由：",@"代理费：",@"发 票 抬 头：  ",@"已 到 款 项  ：",@"已 开 发 票  ：",@"开 票 项 目  ：",@"开 票 类 型  ：",@"发 票 类 型  ：",@"开 票 金 额  ：",@"纳税人识别号  ：",@"基本户开户银行 ：",@"基本户开户账号 ：",@"注册场所地址 ：",@"注册固定电话 ：",@"收件人  ：",@"收 件 地 址  ：",@"联系电话：",@"申请备注：",@"发票号：",@"开票日期：",@"备 注 说 明  ：",nil];
        
    }
    return _titleArray;
}

- (NSArray *)placeHolderArray{
    if (!_placeHolderArray) {
        
        _placeHolderArray = [NSArray arrayWithObjects:@"请选择案件",@"请填写申请人",@"",@"",@"",@"请填写发票抬头",@"",@"",@"请选择开票项目",@"请选择开票类型",@"请选择发票类型",@"请填写开票金额",@"请填写纳税人识别号",@"请填写基本户开户银行",@"请填写基本户开户账号",@"请填写注册场所地址",@"请填写注册固定电话",@"请填写收件人",@"请填写收件地址",@"请填写联系电话",@"请填写申请备注",@"请填写发票号",@"请选择开票日期",@"",nil];
    }
    return _placeHolderArray;
}
- (NSArray *)starArray{
    if (!_starArray) {
        
        _starArray = [NSArray arrayWithObjects:@"*",@"*",@"",@"",@"",@"*",@"",@"",@"*",@"*",@"*",@"*",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"*",@"*",@"",nil];
            }
    return _starArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
